var WebModel = require("WebModel");

// var PlayerInfoData = {
//     nPlayerScore: 100,
//     nPlayerIndex: -1,
//     strPlayerName: "",
//     nIconIndex: 0
// };

var cfg = {
    moveSpeed: 10,
    version: "0.15",
    playerCount: 5,
    cardCount: 10,
    cards: [],
    maxCardNum: 104,
    nScoreSum: 0,
    myPlayerIndex: -1,
    m_rgPublicCards: [],
    m_rgPlayerCards: [],
    m_bGameLayerOpened: false,
    m_rgWaitingSendCardMessages: [],
    m_dicWaitingTakeGroupMessage: {},
    m_nCurrentRound: 1,
    m_bReadyToTakeGroup: false,
    m_rgPlayersInfo: [],
    m_strPlayerName: "",
    m_bInSendCardPhase: true,
    m_flMaskDownHeight: 340,
    m_flMaskUpHeight : 230,
    m_nRoomID : 0,
    m_rgReadyCardsInfo: {},
    m_rgTakingGroupInfo: {},
    m_bContinuedGame : false,
    m_nWaitSendCardTime : 30,

    load: function () 
    {
        cc.log("Take6Model on Load");
        console.log('Take6Model on Load');

        for (var i = 0; i < this.maxCardNum; i++)
        {
            this.cards.push(i + 1);
        }
    },

    getPlayerName: function ()
    {
        return cc.sys.localStorage.getItem("playerName", "");
    },

    setPlayerName: function (strPlayerName)
    {
        cc.sys.localStorage.setItem("playerName", strPlayerName); 
    },

    getRegisterDate: function()
    {
        return cc.sys.localStorage.getItem("registerDate", "");
    },

    setRegisterDate: function(strRegisterDate)
    {
        cc.sys.localStorage.setItem("registerDate", strRegisterDate); 
    },

    getPlayerIconIndex: function ()
    {
        return parseInt(cc.sys.localStorage.getItem("playerIcon", ""));
    },

    setPlayerIconIndex: function (nIconIndex)
    {
        cc.sys.localStorage.setItem("playerIcon", nIconIndex);
    },

    getPlayerIconURL: function ()
    {
        return cc.sys.localStorage.getItem("iconURL", "");
    },

    setPlayerIconURL: function (strIconURL)
    {
        cc.sys.localStorage.setItem("iconURL", strIconURL);
    },

    getPlayerScoreSum: function ()
    {
        return parseInt(cc.sys.localStorage.getItem("scoreSum", ""));
    }, 

    setPlayerScoreSum: function (nScoreSum)
    {
        cc.sys.localStorage.setItem("scoreSum", nScoreSum);
    },

    getPlayerRoundSum: function ()
    {
        return parseInt(cc.sys.localStorage.getItem("roundSum", ""));
    }, 

    setPlayerRoundSum: function (nRoundSum)
    {
        cc.sys.localStorage.setItem("roundSum", nRoundSum);
    },

    getACard: function ()
    {
        var nCurrentCardCount = this.cards.length;
        cc.log("current cards lenght: ", nCurrentCardCount);
        var nCardIndex = parseInt(Math.random() * (nCurrentCardCount));
        cc.log("selecte cardIndex: ", nCardIndex);
        var nCardNum = this.cards.splice(nCardIndex, 1);
        cc.log("card left: ", this.cards);

        return  parseInt(nCardNum);
    },

    getScore: function (nScore)
    {
        this.nScoreSum -= nScore;
        cc.log("current score : ", this.nScoreSum);

        return this.nScoreSum;
    },

    addSpeed: function () 
    {
        cc.find("Canvas").emit('event_player_send_a_card', 
        {
            msg: 'Hello, this is Cocos Creator',
        });
    },

    getAServerCard: function (nPlayerIndex, nCardNum)
    {
        cc.find("Canvas").emit('event_player_select_a_card',
        {
            nPlayerIndex: parseInt(nPlayerIndex),
            nCardNum: parseInt(nCardNum)
        });
    },

    playerSendACard: function (nCardNum)
    {
        cc.find("Canvas").emit('event_player_select_a_card',
        {
            nPlayerIndex: parseInt(this.myPlayerIndex),
            nCardNum: parseInt(nCardNum)
        });
    },

    playerIndex2playerBoardIndex: function (nPlayerIndex)
    {
        if (nPlayerIndex < this.myPlayerIndex)
        {
            return nPlayerIndex;
        }
        else
        {
            return nPlayerIndex - 1;
        }
    },

    playerCreateRoom : function (nPlayerCount)
    {
        var json = 
        {
            "messageType" : "room_create",
            "playerCount" : nPlayerCount,
            "playerName" : this.getPlayerName(),
            "playerIcon" : this.getPlayerIconIndex()
        };

        var jsonStr = JSON.stringify(json);
        WebModel.sendMessageToServer(jsonStr);
    },

    playerJoinRoom : function (nRoomID)
    {
        var json = 
        {
            "messageType" : "room_join",
            "roomID" : nRoomID,
            "playerName" : this.getPlayerName(),
            "playerIcon" : this.getPlayerIconIndex()
        };

        var jsonStr = JSON.stringify(json);
        WebModel.sendMessageToServer(jsonStr);
    },

    playerExitRoom : function ()
    {
        var json = 
        {
            "messageType" : "room_exit"
        };

        var jsonStr = JSON.stringify(json);
        WebModel.sendMessageToServer(jsonStr);
    },

    playerReturnRoom : function ()
    {
        var json = 
        {
            "messageType" : "room_return",
            "roomID" : this.getRoomID(),
            "playerIndex" : this.getPlayerIndex()
        };

        this.myPlayerIndex = this.getPlayerIndex();
        this.m_nRoomID = this.getRoomID();

        var jsonStr = JSON.stringify(json);
        WebModel.sendMessageToServer(jsonStr);
    },

    playerSendCardToServer : function (nCardNum)
    {
        var json = {};
        json.messageType = "game_play";
        json.actionType = "sendACard";
        json.playerIndex = this.myPlayerIndex;
        json.cardSend = nCardNum;
        json.isAI = false;
        json.isTemp = false;

        var jsonStr = JSON.stringify(json);
        WebModel.sendMessageToServer(jsonStr);

        this.m_bInSendCardPhase = false;
    },

    playerTakeGroupToServer : function (nTakeGroup)
    {
        var json = {};
        json.messageType = "game_play";
        json.actionType = "takeAGroup";
        json.playerIndex = this.myPlayerIndex;
        json.groupTake = nTakeGroup;
        json.isAI = false;
        json.isTemp = false;

        var jsonStr = JSON.stringify(json);
        WebModel.sendMessageToServer(jsonStr);
    },

    kickOpponentOutRequest : function (nPlayerIndex)
    {
        var json = {};
        json.messageType = "room_kick_out";
        json.playerIndex = nPlayerIndex;

        var jsonStr = JSON.stringify(json);
        WebModel.sendMessageToServer(jsonStr, true);
    },

// pase replys method
    paseUserDataMessageJson : function (userDataMessageJson)
    {   
        var playerName = userDataMessageJson.userName;
        var iconURL = userDataMessageJson.iconURL;
        var scoreSum = userDataMessageJson.userScore;
        var roundSum = userDataMessageJson.userRound;

        this.setPlayerName(playerName);
        this.setPlayerIconURL(iconURL);
        this.setPlayerScoreSum(scoreSum);
        this.setPlayerRoundSum(roundSum);
    },

    paseCreateRoomMessageJson : function (createRoomMessageJson)
    {
        this.myPlayerIndex = createRoomMessageJson.playerIndex;
        this.playerCount = createRoomMessageJson.playerCount;
        this.m_nCurrentRound = 1;

        if (this.playerCount == 3)
        {
            this.cardCount = 16;
        }
        else if (this.playerCount == 4)
        {
            this.cardCount = 12;
        }
        else // this.playerCount == 5
        {
            this.cardCount = 10;
        }

        var room = createRoomMessageJson.roomID;
        this.m_nRoomID = room;

        if (cc.sys.platform != cc.sys.WECHAT_GAME)
        {
            this.savePlayerIndex(this.myPlayerIndex);
            this.saveRoomID(this.m_nRoomID);
        }

        cc.find("Canvas").emit('event_create_room_success',
        {
            nRoomID: parseInt(room),
        });
    },

    paseJoinRoomMessageJson : function (joinRoomMessageJson)
    {
        if (this.myPlayerIndex < 0)
        {
            this.myPlayerIndex = joinRoomMessageJson.playerIndex;
            this.playerCount = joinRoomMessageJson.playerCount;
            this.m_nRoomID = joinRoomMessageJson.roomID;
            this.m_nCurrentRound = 1;
        }

        var rgReadyPlayers = joinRoomMessageJson.readyPlayers;

        if (this.playerCount == 3)
        {
            this.cardCount = 16;
        }
        else if (this.playerCount == 4)
        {
            this.cardCount = 12;
        }
        else // this.playerCount == 5
        {
            this.cardCount = 10;
        }

        if (cc.sys.platform != cc.sys.WECHAT_GAME)
        {
            this.savePlayerIndex(this.myPlayerIndex);
            this.saveRoomID(this.m_nRoomID);
        }

        cc.log("readyPlayers: ", rgReadyPlayers);

        cc.find("Canvas").emit('event_join_room_success',
        {
            rgPlayerNames: rgReadyPlayers,
        });
    },

    paseExitRoomMessageJson : function (exitRoomMessageJson)
    {
        this.savePlayerIndex(-1);
        this.saveRoomID(0);

        this.myPlayerIndex = -1;

        cc.find("Canvas").emit('event_exit_room_success');
    },

    parseGameStartMessageJson : function (gameStartMessageJson)
    {
        this.m_bInSendCardPhase = true;
        this.m_rgWaitingSendCardMessages = [];
        this.m_dicWaitingTakeGroupMessage = {};

        if (cc.sys.platform === cc.sys.WECHAT_GAME)
        {
            this.savePlayerIndex(this.myPlayerIndex);
            this.saveRoomID(this.m_nRoomID);
        }

        this.m_rgPublicCards = gameStartMessageJson.cardsGroup;
        this.m_rgPlayerCards = gameStartMessageJson.playerCards[this.myPlayerIndex];
        cc.log("this.m_rgPlayerCards : ", this.m_rgPlayerCards);
        var rgPlayerInfo = gameStartMessageJson.playerInfos;

        for (var i = 0; i < this.playerCount; i++) 
        {
            var playerInfo = {};
            playerInfo.nPlayerScore = rgPlayerInfo[i].playerScore;
            playerInfo.nPlayerIndex = i;
            playerInfo.nPlayerIcon = rgPlayerInfo[i].playerIcon;
            
            if (i == this.myPlayerIndex)
            {
                playerInfo.strPlayerName = this.getPlayerName();
            }
            else
            {
                playerInfo.strPlayerName = rgPlayerInfo[i].playerName;
            }

            this.m_rgPlayersInfo[i] = playerInfo;
        }

        cc.find("Canvas").emit('event_start_game',{});
    },

    parseGameContinueMessageJson : function (gameContinueMessageJson)
    {
        this.m_rgWaitingSendCardMessages = [];
        this.m_dicWaitingTakeGroupMessage = {};

        this.m_bContinuedGame = true;

        this.savePlayerIndex(this.myPlayerIndex);
        this.saveRoomID(this.m_nRoomID);

        this.playerCount = gameContinueMessageJson.playerCount;

        this.m_rgPublicCards = gameContinueMessageJson.cardsGroup;
        this.m_rgPlayerCards = gameContinueMessageJson.playerCards[this.myPlayerIndex];
        var rgPlayerInfo = gameContinueMessageJson.playerInfos;

        cc.log("m_rgPlayerCards : ", this.m_rgPlayerCards);

        for (var i = 0; i < this.playerCount; i++) 
        {
            var playerInfo = {};
            playerInfo.nPlayerScore = rgPlayerInfo[i].playerScore;
            playerInfo.nPlayerIndex = rgPlayerInfo[i].playerIndex;
            playerInfo.nPlayerIcon = rgPlayerInfo[i].playerIcon;
            
            if (i == this.myPlayerIndex)
            {
                playerInfo.strPlayerName = this.getPlayerName();
            }
            else
            {
                playerInfo.strPlayerName = rgPlayerInfo[i].playerName;
            }

            this.m_rgPlayersInfo[i] = playerInfo;
        }

        // for continue
        this.m_nCurrentRound = gameContinueMessageJson.roundIndex;
        this.m_rgReadyCardsInfo = gameContinueMessageJson.readyCards;
        this.m_rgTakingGroupInfo = gameContinueMessageJson.takingGroup;

        var bSendedCardThisRound = false;
        for (var i = 0; i < this.m_rgReadyCardsInfo.length; i++)
        { 
            var readyCardDic = this.m_rgReadyCardsInfo[i];
            if (readyCardDic.playerIndex == this.myPlayerIndex)
            {
                bSendedCardThisRound = true;
            }
        }
        this.m_bInSendCardPhase = !bSendedCardThisRound; 

        var nCardInitialCount = 0;
        if (this.playerCount == 3)
        {
            nCardInitialCount = 16;
        }
        else if (this.playerCount == 4)
        {
            nCardInitialCount = 12;
        }
        else // this.playerCount == 5
        {
            nCardInitialCount = 10;
        }

        this.cardCount = nCardInitialCount - this.m_nCurrentRound + 1;
        if (this.cardCount <= 0)
        {
            this.cardCount += nCardInitialCount;
        }

        if (bSendedCardThisRound)
        {
            this.cardCount -= 1;
            if (this.cardCount < 0)
            {
                this.cardCount += nCardInitialCount;
            }
        }

        cc.log(" this.m_nCurrentRound : ", this.m_nCurrentRound);
        cc.log(" this.m_rgReadyCardsInfo : ", this.m_rgReadyCardsInfo);
        cc.log(" this.m_rgTakingGroupInfo : ", this.m_rgTakingGroupInfo);

        cc.find("Canvas").emit('event_continue_game',{});
    },

    parseGamePlayMessageJson : function (gamePlayMessageJson)
    {
        var actionType = gamePlayMessageJson.actionType;
        var nRound = gamePlayMessageJson.roundIndex;
        var playerIndex = gamePlayMessageJson.playerIndex;
        var isAI = gamePlayMessageJson.isAI;
        var isTemp = gamePlayMessageJson.isTemp;

        cc.log("parseGamePlayMessageJson isTemp : ", isTemp);

        if (actionType == "sendACard")
        {
            if (this.m_bGameLayerOpened == false || this.m_nCurrentRound < nRound)
            {
                if (this.m_rgWaitingSendCardMessages.indexOf() < 0)
                {
                    console.log("push once");
                    this.m_rgWaitingSendCardMessages.push(gamePlayMessageJson);
                }
            }
            else 
            {
                var cardSend = gamePlayMessageJson.cardSend;
                cc.find("Canvas").emit('event_player_select_a_card',
                {
                    nPlayerIndex: parseInt(playerIndex),
                    nCardNum: parseInt(cardSend),
                    bIsAI: isAI,
                    bIsTemp: isTemp
                });
            }            
        }
        else //actionType == "takeAGroup"
        {
            if (this.m_bReadyToTakeGroup == false || this.m_nCurrentRound < nRound)
            {
                this.m_dicWaitingTakeGroupMessage = gamePlayMessageJson;
            }
            else 
            {
                var takeGroup = gamePlayMessageJson.groupTake;
                cc.find("Canvas").emit('event_player_select_a_group',
                {
                    nPlayerIndex: parseInt(playerIndex),
                    nTakeGroup: parseInt(takeGroup),
                    bIsAI: isAI,
                    bIsTemp: isTemp
                });
            } 
        }
    },

    tryToParseWaitingGamePlayMessageJson : function ()
    {
        if (this.m_bGameLayerOpened && this.m_rgWaitingSendCardMessages.length > 0)
        {
            // while (this.m_rgWaitingSendCardMessages.length > 0)
            // {
                console.log("shift once");
                this.parseGamePlayMessageJson(this.m_rgWaitingSendCardMessages.shift());
            // }   
        }
    },

    tryToParseWaitingTakeGroupMessageJson : function ()
    {
        if (this.m_dicWaitingTakeGroupMessage.messageType) //此种方法判断是否为空对象
        {
            var takeGroupMessageJson = this.m_dicWaitingTakeGroupMessage;
            this.m_dicWaitingTakeGroupMessage = {};
            this.parseGamePlayMessageJson(takeGroupMessageJson);
        }
    },

    getPublicCardNum : function (nGroupIndex, nIndexInGroup)
    {
        nIndexInGroup = arguments[1] ? arguments[1] : 0;

        if (nIndexInGroup >= this.m_rgPublicCards[nGroupIndex].length)
        {
            return -1;
        }

        return this.m_rgPublicCards[nGroupIndex][nIndexInGroup];
    },

    getPlayerCardNum : function (nIndex)
    {
        return this.m_rgPlayerCards[nIndex];
    },

    saveRoomID : function (nRoomID)
    {
        cc.sys.localStorage.setItem("RoomID", nRoomID);
    },

    getRoomID : function ()
    {
        return parseInt(cc.sys.localStorage.getItem("RoomID", "0"));
    },

    savePlayerIndex : function (nPlayerIndex)
    {
        cc.sys.localStorage.setItem("PlayerIndex", nPlayerIndex);
    },

    getPlayerIndex : function ()
    {
        return parseInt(cc.sys.localStorage.getItem("PlayerIndex", "-1"));
    },

    playerTimeIsUp : function (nPlayerIndex)
    {
        
    },
};
cfg.load();

module.exports = cfg;